<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <template #header>
                <el-radio-group v-model="keyScene" size="large">
                    <el-radio-button label="对话密钥" value="chat" />
                    <el-radio-button label="向量密钥" value="vector" />
                    <el-radio-button label="重排密钥" value="ranking" />
                    <el-radio-button label="AI绘画" value="draws" />
                    <el-radio-button label="AI音乐" value="music" />
                    <el-radio-button label="AI视频" value="video" />
                    <!--  <el-radio-button label="AI搜索" value="search" /> -->
                    <el-radio-button label="语音播报" value="voice_speech" />
                    <el-radio-button label="语音输入" value="voice_transfer" />
                </el-radio-group>
            </template>

            <div v-loading="pager.loading" class="flex">
                <ul class="menus">
                    <li
                        v-for="(item, index) in channels"
                        :key="index"
                        :class="{
                            'active': index === keyIndex,
                            'disabled': item.is_disable
                        }"
                        @click="handleSwitch(index)"
                    >
                        <el-image :src="item.logo" class="w-[16px] h-[16px] shrink-0" />
                        <span class="ml-1">{{ item.name }}</span>
                    </li>
                </ul>
                <div class="flex-1 overflow-hidden">
                    <div class="flex justify-between">
                        <el-button type="primary" v-perms="['setting:ai:secret:add']" @click="handleEditor('add')">
                            <template #icon>
                                <icon name="el-icon-Plus" />
                            </template>
                            <span>添加Key</span>
                        </el-button>
                        <el-form class="mb-[-16px]" :model="queryParams" :inline="true">
                            <el-form-item style="margin-right: 10px;">
                                <el-input
                                    v-model="queryParams.keyword"
                                    class="w-[150px]"
                                    placeholder="请输入关键词"
                                    @keyup.enter="resetPaging"
                                />
                            </el-form-item>
                            <el-form-item style="margin-right: 10px;">
                                <el-select
                                    v-model="queryParams.is_disable"
                                    class="w-[100px]"
                                    placeholder="状态"
                                >
                                    <el-option value="" label="全部"/>
                                    <el-option value="1" label="启用"/>
                                    <el-option value="0" label="禁用"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="resetPaging">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <el-table :data="pager.lists" :loading="pager.loading" size="large" class="mt-4">
                        <template v-if="['xunfei'].includes(channels[keyIndex]?.channel)">
                            <el-table-column label="APPID" prop="app_id" min-width="100" show-tooltip-when-overflow />
                            <el-table-column label="APIKey" prop="api_key" min-width="200" show-tooltip-when-overflow />
                            <el-table-column label="APISecret" prop="api_secret" min-width="100" />
                        </template>
                        <template v-else-if="['minimax'].includes(channels[keyIndex]?.channel)">
                            <el-table-column label="GroupId" prop="app_id" min-width="100" show-tooltip-when-overflow />
                            <el-table-column label="APIKey" prop="api_key" min-width="200" show-tooltip-when-overflow />
                        </template>
                        <template v-else-if="['baidu'].includes(channels[keyIndex]?.channel)">
                            <el-table-column label="APPID" prop="app_id" min-width="100" show-tooltip-when-overflow />
                            <el-table-column label="APIKey" prop="api_key" min-width="200" show-tooltip-when-overflow />
                        </template>
                        <template v-else-if="['doubao'].includes(channels[keyIndex]?.channel) && queryParams.scene === 'draws'">
                            <el-table-column label="APIKey" prop="api_key" min-width="200" show-tooltip-when-overflow />
                            <el-table-column label="APISecret" prop="api_secret" min-width="100" />
                        </template>
                        <template v-else>
                            <el-table-column label="APIKey" prop="api_key" min-width="200" show-tooltip-when-overflow />
                        </template>
                        <el-table-column label="错误" prop="error" min-width="100" show-tooltip-when-overflow>
                            <template #default="{ row }">
                                <span v-if="row?.error" class="text-sm text-error">{{ row?.error }}</span>
                                <span class="text-sm">-</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" prop="is_disable" min-width="80">
                            <template #default="{ row }">
                                <div
                                    v-perms="['setting:ai:secret:disable']"
                                    @click="handleDisable(row.id, !row.is_disable)"
                                    class="cursor-pointer"
                                >
                                    <el-tag v-if="row.is_disable === 0">正常</el-tag>
                                    <el-tag v-else type="danger">停用</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" prop="create_time" min-width="175" />
                        <el-table-column label="操作" width="120" fixed="right">
                            <template #default="{ row }">
                                <el-button
                                    v-perms="['setting:ai:secret:edit']"
                                    type="primary"
                                    link
                                    @click="handleEditor('edit', row)"
                                >
                                    编辑
                                </el-button>
                                <el-button
                                    v-perms="['setting:ai:secret:delete']"
                                    type="danger"
                                    link
                                    @click="handleDelete(row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="flex justify-end mt-4">
                        <paging v-model="pager" @change="queryLists" />
                    </div>
                </div>
            </div>
        </el-card>

        <!-- 编辑器 -->
        <editor
            v-if="showEdit"
            ref="editorRef"
            :scene="keyScene"
            :mark="channels[keyIndex].mark"
            :channel="channels[keyIndex].channel"
            @success="queryLists"
            @close="showEdit = false"
        />
    </div>
</template>

<script setup lang="ts">
import { usePaging } from '@/hooks/usePaging'
import aiSecretApi from '@/api/setting/ai/secret'
import feedback from '@/utils/feedback'
import Editor from './editor.vue'

const showEdit = ref(false)
const editorRef = shallowRef<InstanceType<typeof Editor>>()

const keyIndex = ref<number>(3)
const keyScene = ref<string>('chat')
const channels = ref<any[]>([])

// 查询参数
const queryParams = reactive({
    scene: keyScene.value,
    channel: '',
    keyword: '',
    is_disable: ''
})

// 分页查询
const { pager, queryLists, resetPaging } = usePaging({
    fetchFun: aiSecretApi.lists,
    params: queryParams
})

/**
 * 处理编辑
 *
 * @param {string} type
 * @param {any} row
 * @returns {Promise<void>}
 */
const handleEditor = async (type: string, row?: any): Promise<void> => {
    showEdit.value = true
    await nextTick()
    editorRef.value?.open(type, row)
}

/**
 * 处理删除
 *
 * @param {number} id
 * @returns {Promise<void>}
 */
const handleDelete = async (id: number): Promise<void> => {
    feedback.confirm('确定要删除此项数据吗?')
        .then(async () => {
            await aiSecretApi.delete(id)
            feedback.msgSuccess('删除成功')
            await resetPaging()
        }).catch(() => {})
}

/**
 * 切换选项
 *
 * @param {number} index
 */
const handleSwitch = async (index: number) => {
    keyIndex.value = index
    queryParams.channel = channels.value[keyIndex.value].mark
    await resetPaging()
}

/**
 * 处理停用
 *
 * @param {number} id
 * @param {boolean} status
 */
const handleDisable = async (id: number, status: boolean) => {
    const message = status ? '您确定要停用该密钥吗?' : '您确定要启用该密钥吗?'
    const success = status ? '停用成功' : '启用成功'
    feedback.confirm(message)
        .then(async () => {
            await aiSecretApi.disable(id)
            feedback.msgSuccess(success)
            await resetPaging()
        }).catch(() => {})
}

watch(
    () => keyScene.value,
    async (val) => {
        channels.value = await aiSecretApi.channel(keyScene.value)
        keyIndex.value = 0
        queryParams.scene = val
        queryParams.channel = ''
        queryParams.keyword = ''
        queryParams.is_disable = ''
        if (channels.value.length > 0) {
            queryParams.channel = channels.value[keyIndex.value].mark
        }
        await resetPaging()
    },
    {
        immediate: true
    }
)
</script>

<style scoped lang="scss">
.menus {
    flex-shrink: 0;
    min-width: 130px;
    padding-right: 20px;
    margin-right: 20px;
    border-right: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
    li {
        display: flex;
        align-items: center;
        min-width: 90px;
        height: 36px;
        padding: 0 12px;
        margin-bottom: 10px;
        font-size: 13px;
        line-height: 36px;
        color: var(--el-text-color-regular);
        text-align: left;
        white-space: nowrap;
        cursor: pointer;
        border-radius: 4px;
        &.disabled {
            color: var(--el-text-color-disabled) !important;
        }
        &.active {
            color: var(--el-color-primary);
            background-color: #f3f6f9;
        }
        &:hover {
            color: var(--el-color-primary);
        }
    }
}
</style>
